package org.journal.service;

import java.util.ArrayList;
import java.util.List;

import org.journal.dao.AuthoritiesDAO;
import org.journal.dao.UserDAO;
import org.journal.dto.UserDTO;
import org.journal.entity.AuthoritiesEntity;
import org.journal.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class UserServiceImpl implements UserService {

	private static final Logger log = LoggerFactory
			.getLogger(UserServiceImpl.class);

	@Autowired
	private UserDAO userDAO;
	@Autowired
	private AuthoritiesDAO authoritiesDAO;

	@Transactional
	public UserEntity getUserByUsername(String username) {

		return userDAO.getUserByName(username);
	}

	public UserEntity getUserById(int id) {
		return userDAO.getUserById(id);

	}

	public User getUserAuthorizationDetails(UserEntity user) {

		UserDTO userDetails = null;
		if (user != null) {
			List<GrantedAuthority> authorities = new ArrayList<>();
			List<AuthoritiesEntity> userRoles = authoritiesDAO
					.getUserAuthorities(user);

			if (userRoles != null) {
				for (AuthoritiesEntity role : userRoles) {
					authorities.add(new SimpleGrantedAuthority(role
							.getAuthority()));
				}
			}

			userDetails = new UserDTO(user.getUsername(), user.getPassword(),
					user.isEnabled(), true, true, true, authorities);
			userDetails.setId(user.getIdUser());
			System.out.println(user.getPassword());
			log.debug("user = {}", userDetails);
		}
		return userDetails;

	}
}
